Here is my doInBackground func:
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if(type.equals("POST") || type.equals("PUT")){
params.add(new BasicNameValuePair("id", pid));
params.add(new BasicNameValuePair("name", name));
}else if(type.equals("DELETE")){
Log.d("DELETE:", pid);
params.add(new BasicNameValuePair("id", pid));
}
JSONObject json = jsonParser.makeHttpRequest(url, type, params);
Log.d("Create Response", json.toString());
if(type.equals("GET")){
try {
jsonRows = json.getJSONArray("rows");
for(int i = 0; i<jsonRows.length();i++){
JSONObject p = (JSONObject)jsonRows.get(i);
aList.add(p.getString("ID") + " - " +p.getString("Name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
try{
String result = json.getString("results");
return result;
}catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
my httpDelete code :
else if(method == "DELETE"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String param = null;
for (NameValuePair nvp : params){
param = nvp.getValue();
url += "/" + param;
Log.d("url = ", url);
}
HttpDelete httpDelete = new HttpDelete(url);
HttpResponse httpResponse = httpClient.execute(httpDelete);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
and node.js server :
app.delete('/api/db/:id', function(req, res){
var id = req.params.id;
res.setHeader('content-type', 'application/json');
dbPool.getConnection(function(objErr, objConn){
if(objErr){
sendError(res, 503, 'error', 'connection', objErr); //503 - Service Unavailable
}else{
objConn.query("DELETE FROM person WHERE ID = ? ",[id], function(Err, Rows, Fields){
if(Err){
sendError(res, 500, 'error', 'query', Err);
}else{
res.send({
results : 'success'
});
objConn.release();
gcmSend();
}//else
});
}//else
});
});
Errors:
09-24 06:35:12.386: E/AndroidRuntime(1908): FATAL EXCEPTION: AsyncTask #4
09-24 06:35:12.386: E/AndroidRuntime(1908): java.lang.RuntimeException: An error occured while executing doInBackground()
09-24 06:35:12.386: E/AndroidRuntime(1908): at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-24 06:35:12.386: E/AndroidRuntime(1908): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.lang.Thread.run(Thread.java:841)
09-24 06:35:12.386: E/AndroidRuntime(1908): Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 36: -----192.168.1.11:3030/api/db/9
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.net.URI.create(URI.java:727)
09-24 06:35:12.386: E/AndroidRuntime(1908): at org.apache.http.client.methods.HttpDelete.<init>(HttpDelete.java:68)
09-24 06:35:12.386: E/AndroidRuntime(1908): at com.argenit.monitor.JSONParser.makeHttpRequest(JSONParser.java:86)
09-24 06:35:12.386: E/AndroidRuntime(1908): at com.argenit.monitor.MainPage$HttpAsyncTask.doInBackground(MainPage.java:137)
09-24 06:35:12.386: E/AndroidRuntime(1908): at com.argenit.monitor.MainPage$HttpAsyncTask.doInBackground(MainPage.java:1)
09-24 06:35:12.386: E/AndroidRuntime(1908): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-24 06:35:12.386: E/AndroidRuntime(1908): ... 4 more
Anyone help me?
Last logcat before error :
Log.d("url = ", url); -> 09-24 06:40:45.066: D/url =(1978):
----/192.168.1.11:3030/api/db/8
Related
I trying to get simple json from URL. But I get exception on line c.connect(). I added permission for Internet in manifest.
Tried 5-6 codes, but everytime I get break on connection everytime. In debbuging I get response code -1 but going to final block on c.connect() line.
String result = getJSON("http://api.wipmania.com/json");
public String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(newInputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
Here is Log:
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: FATAL EXCEPTION: main
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: Process: com.testapp.alex.testmaapp, PID: 2529
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.testapp.alex.testmaapp/com.testapp.alex.testmaapp.SumActivity}: android.os.NetworkOnMainThreadException
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: Caused by: android.os.NetworkOnMainThreadException
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.testapp.alex.testmaapp.SumActivity.makeRequest(SumActivity.java:82)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.testapp.alex.testmaapp.SumActivity.onCreate(SumActivity.java:51)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6237)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
The logcat you posted suggests that you are trying to make this call on Main Thread and it isn't possible, so you have to start another Trhead; check this:
final Runnable connect = new Runnable() {
Handler progress = new Handler();
#Override
public void run() {
String response = getJSON("http://api.wipmania.com/json");
progress.post(new Runnable() {
#Override
public void run() {
//do what you want with response
}
});
}
};
and call in this way:
new Thread(connect).start();
Anyway there are a lot of libraries that make http request for you, in a very simple way.
Check for Robospice or for Retrofit.
In my last project I used Retrofit, and it's very comfortable.
This is another guide for using Retrofit
try this code
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
"http://bla/bla/bla");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
You have already opened connection with u.openConnection(); so don't need to call c.connect().
Check this link for more information:
Try this way:
public String makeRequest(String uri, String json) {
HttpURLConnection urlConnection;
String data = json;
String result = null;
try {
// Connect
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection
.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
// Read
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(),
"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
System.out.println("result result result: " + result.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
I want to download a 100MB file using streams:
I used an AsyncTask class to make download:
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = connection.getInputStream();
outputStream = new FileOutputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), params[1]));
byte[] data = new byte[104857600];
int length = inputStream.read(data);
outputStream.write(data, 0, length);
} catch (Exception e) {
Log.e(TAG, "Unable to download file with DownloadTask: " + e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
connection.disconnect();
} catch (Exception e) {
Log.e(TAG, "Unable to cancel download file with DownloadTask: " + e.getMessage());
}
}
return null;
}
I'm sure I used the following permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
But when I test my app, it crashes and I see in logcat Out of memory on a 104857616-byte allocation:
10-02 10:28:35.578 29630-2246/com.example.myapp E/dalvikvm-heap: Out of memory on a 104857616-byte allocation.
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: Caused by: java.lang.OutOfMemoryError
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at com.example.myapp.DownloaderActivity$DownloadTask.doInBackground(DownloaderActivity.java:126)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at com.example.myapp.DownloaderActivity$DownloadTask.doInBackground(DownloaderActivity.java:107)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
Is there some way to download large files or accept 104857600 bytes (100MB)?
You have write data portion by portion as chunk. System don't provide huge memory at once for an operation.
Replace those lines:
byte[] data = new byte[104857600];
int length = inputStream.read(data);
outputStream.write(data, 0, length);
by:
byte [] buffer = new byte[1024];
int bytesRead = 0;
while((bytesRead =input.read(buffer)) != -1) {
outputStream .write(buffer, 0,
bytesRead);
}
I've recently studyed android by myself.
and I tried Using Fragment by following my Textbook
but I met an error even though I typed codes exactly the same as my textbook.
Can you guys explain to me what is wrong?
This is MainActivity.java
package com.example.ex_1;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static class CounterFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.counterfragment, container, false);
Button btnIncrease = (Button)root.findViewById(R.id.btnincrease);
final TextView textCounter = (TextView)root.findViewById(R.id.txtcounter);
btnIncrease.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = Integer.parseInt(textCounter.getText().toString());
textCounter.setText(Integer.toString(count + 1));
}
});
return root;
}
}
}
This is activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="~~"/>
<fragment
android:name="com.example.ex_1.MainActivity$CounterFragment"
android:id="#+id/counterfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And the error is
09-24 07:40:08.329: E/AndroidRuntime(1794): FATAL EXCEPTION: main
09-24 07:40:08.329: E/AndroidRuntime(1794): Process: com.example.ex_1, PID: 1794
09-24 07:40:08.329: E/AndroidRuntime(1794): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ex_1/com.example.ex_1.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.access$800(ActivityThread.java:144)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.os.Handler.dispatchMessage(Handler.java:102)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.os.Looper.loop(Looper.java:135)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.main(ActivityThread.java:5221)
09-24 07:40:08.329: E/AndroidRuntime(1794): at java.lang.reflect.Method.invoke(Native Method)
09-24 07:40:08.329: E/AndroidRuntime(1794): at java.lang.reflect.Method.invoke(Method.java:372)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
09-24 07:40:08.329: E/AndroidRuntime(1794): Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Activity.setContentView(Activity.java:2144)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.example.ex_1.MainActivity.onCreate(MainActivity.java:19)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Activity.performCreate(Activity.java:5937)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
09-24 07:40:08.329: E/AndroidRuntime(1794): ... 10 more
09-24 07:40:08.329: E/AndroidRuntime(1794): Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.ex_1.MainActivity$CounterFragment that is not a Fragment
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Fragment.instantiate(Fragment.java:606)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Fragment.instantiate(Fragment.java:582)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2108)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Activity.onCreateView(Activity.java:5286)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
09-24 07:40:08.329: E/AndroidRuntime(1794): ... 20 more
09-24 07:40:08.329: E/AndroidRuntime(1794): Caused by: java.lang.ClassCastException
09-24 07:40:08.329: E/AndroidRuntime(1794): ... 25 more
problem is that you set your api level too low, so it use "support" version of fragment, instead of "base" fragment
put "min api level" at 11 in your androidmanifest, remove dependency to "support" library, remove "import android.support.v4.app.Fragment" and replace it with "import android.app.fragment" and it should work
change
public class MainActivity extends Activity {
to
public class MainActivity extends FragmentActivity {
10-23 00:41:00.705: E/AndroidRuntime(3622): FATAL EXCEPTION: AsyncTask #1
10-23 00:41:00.705: E/AndroidRuntime(3622): java.lang.RuntimeException: An error occured while executing doInBackground()
10-23 00:41:00.705: E/AndroidRuntime(3622): at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-23 00:41:00.705: E/AndroidRuntime(3622): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.lang.Thread.run(Thread.java:856)
10-23 00:41:00.705: E/AndroidRuntime(3622): Caused by: java.lang.IllegalStateException: Content has been consumed
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.entity.BasicHttpEntity.writeTo(BasicHttpEntity.java:126)
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.entity.HttpEntityWrapper.writeTo(HttpEntityWrapper.java:101)
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.conn.BasicManagedEntity.writeTo(BasicManagedEntity.java:126)
10-23 00:41:00.705: E/AndroidRuntime(3622): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:51)
10-23 00:41:00.705: E/AndroidRuntime(3622): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:1)
10-23 00:41:00.705: E/AndroidRuntime(3622): at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-23 00:41:00.705: E/AndroidRuntime(3622): ... 4 more
Hi
I am calling my web service using gson library I am getting exception.I don't know why it is occur .could you please tell me removing this error
I will give you steps what I did ..
1 )Main activity
public class Appliacationload extends Activity implements WebserviceCallBack{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appliacationload);
/*WebserviceMethod callDepartudeDashboard=new WebserviceMethod();
callDepartudeDashboard.setObserver(this);
callDepartudeDashboard.getwebService(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=hnh");*/
RequestTask callWebService=new RequestTask();
callWebService.setObserver(this);
callWebService.execute(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=vic");
}
#Override
public void getWebserviceResponse(String response) {
// TODO Auto-generated method stub
Log.d("response", response);
}
}
and I have one holder and RequestTask class to call webservice and return call back .
public class RequestTask extends AsyncTask<String, String, String>{
private WebserviceCallBack callBack;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog= new ProgressDialog((Context) callBack);
super.onPreExecute();
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Webservice Call...");
progressDialog.setCancelable(true);
progressDialog.show();
}
#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){
Reader reader = new InputStreamReader(response.getEntity().getContent());
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
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..\
progressDialog.hide();
} catch (IOException e) {
//TODO Handle problems..
progressDialog.hide();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
if(callBack!=null){
callBack.getWebserviceResponse(result);
}
progressDialog.hide();
}
public void setObserver(WebserviceCallBack callback){
callBack=callback;
}
}
Holder class;
public class Holder {
List<deparaturedaseboarddto> data;
}
New Update when I change my request task like that ..
public class RequestTask extends AsyncTask<String, String, InputStream>{
private WebserviceCallBack callBack;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog= new ProgressDialog((Context) callBack);
super.onPreExecute();
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Webservice Call...");
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected InputStream 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){
/*Reader reader = new InputStreamReader(response.getEntity().getContent());
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();*/
return response.getEntity().getContent();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..\
progressDialog.hide();
} catch (IOException e) {
//TODO Handle problems..
progressDialog.hide();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
//Do anything with response..
if(callBack!=null){
callBack.getWebserviceResponse(result);
}
progressDialog.dismiss();
progressDialog=null;
}
public void setObserver(WebserviceCallBack callback){
callBack=callback;
}
}
and call back like that
public interface WebserviceCallBack {
public void getWebserviceResponse(InputStream result);
}
and main activity like that
public class Appliacationload extends Activity implements WebserviceCallBack{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appliacationload);
/*WebserviceMethod callDepartudeDashboard=new WebserviceMethod();
callDepartudeDashboard.setObserver(this);
callDepartudeDashboard.getwebService(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=hnh");*/
RequestTask callWebService=new RequestTask();
callWebService.setObserver(this);
callWebService.execute(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=vic");
}
#Override
public void getWebserviceResponse(InputStream result) {
// TODO Auto-generated method stub
Reader reader = new InputStreamReader(result);
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
Log.d("-----", "naveen");
}
I got this exception why ..?I am sending the input stream on call back and make here in main activity ..
exception:
10-23 03:07:33.956: E/AndroidRuntime(22412): FATAL EXCEPTION: main
10-23 03:07:33.956: E/AndroidRuntime(22412): android.os.NetworkOnMainThreadException
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
10-23 03:07:33.956: E/AndroidRuntime(22412): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
10-23 03:07:33.956: E/AndroidRuntime(22412): at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:161)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.io.InputStreamReader.read(InputStreamReader.java:244)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.stream.JsonReader.fillBuffer(JsonReader.java:1298)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.stream.JsonReader.nextQuotedValue(JsonReader.java:1028)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.stream.JsonReader.nextName(JsonReader.java:796)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:178)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:95)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:183)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.Gson.fromJson(Gson.java:805)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.Gson.fromJson(Gson.java:743)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.firstgroup.applicationload.Appliacationload.getWebserviceResponse(Appliacationload.java:48)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.firstgroup.webservice.RequestTask.onPostExecute(RequestTask.java:77)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.firstgroup.webservice.RequestTask.onPostExecute(RequestTask.java:1)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.AsyncTask.finish(AsyncTask.java:631)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.Looper.loop(Looper.java:137)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.lang.reflect.Method.invoke(Method.java:511)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-23 03:07:33.956: E/AndroidRuntime(22412): at dalvik.system.NativeStart.main(Native Method)
The reason is you can only consume Content from Entity once.
You did it twice (maybe without you knowing it) in here
Reader reader = new InputStreamReader(response.getEntity().getContent());
and here
response.getEntity().writeTo(out);
I know this is sounds a little weird but actually the writeTo() function will get content from the entity to write to the OutputStream. You can see it in the documentation here
Another workaround you can use is turning it to string and let GSON handle it
#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){
responseString = EntityUtils.toString(response.getEntity()); // content will be consume only once
Gson gson = new Gson();
Holder response1 = gson.fromJson(responseString, Holder.class);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..\
progressDialog.hide();
} catch (IOException e) {
//TODO Handle problems..
progressDialog.hide();
}
return responseString;
}
I hope my answer can help you!
Got my code in a try-catch loop. It runs fine on my phone (Samsung Galaxy S3, but give a runtime error in the Eclipse emulator.
The error appeared after I added a color setting to the method and used a GradientDrawable as the background for my button (even though this seems to work fine at other locations).
I'm totally lost here... Please have a look, THANKS!!
Code that generates the error
Note: I put a breakpoint on "return super.onContextItemSelected(item);", runtime error is generated on/after the return statement.
#SuppressLint("NewApi") #SuppressWarnings("deprecation")
#Override
public boolean onContextItemSelected(MenuItem item) {
int timerLocation = findTimer(item.getGroupId());
if (timerLocation > -1)
{
final MyCountDownTimer selectedFrag = this.myTimersList.get(timerLocation).fragmentRef;
switch (item.getItemId()) {
case R.id.timer_settings:
// Open timer specific options menu:
defaultSettingsMenu(selectedFrag);
return true;
default:
return super.onContextItemSelected(item);
}
}
else timerClickScreen.setText("ERROR: timer not found: " + String.valueOf(item.getGroupId()) + ", "+ String.valueOf(timerLocation));
return super.onContextItemSelected(item);
}
Main method:
private void defaultSettingsMenu(MyCountDownTimer selectedFragIN)
{
try
{
final MyCountDownTimer selectedFrag = selectedFragIN;
final Dialog dialog_settings = new Dialog(this);
dialog_settings.setContentView(R.layout.timer_set_options);
if (selectedFrag == null) dialog_settings.setTitle(R.string.default_settings_for_timer);
else dialog_settings.setTitle(R.string.timer_settings);
if (selectedFrag == null)
{
// Set title color:
dialog_settings.getWindow().setTitleColor(getDefaultColor());
// Set divider color:
int dividerTop = dialog_settings.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider1 = dialog_settings.findViewById(dividerTop);
divider1.setBackgroundColor(getDefaultColor());
}
else
{
// Set title color:
dialog_settings.getWindow().setTitleColor(selectedFrag.getTimerColor());
// Set divider color:
int dividerTop = dialog_settings.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider1 = dialog_settings.findViewById(dividerTop);
divider1.setBackgroundColor(selectedFrag.getTimerColor());
}
final TextView[] settingsItems = new TextView[8];
settingsItems[0]= (TextView) dialog_settings.findViewById(R.id.timerSettings_item1);
settingsItems[1]= (TextView) dialog_settings.findViewById(R.id.timerSettings_item2);
...
final Spinner[] settingsSetting = new Spinner[7];
settingsSetting[0]= (Spinner) dialog_settings.findViewById(R.id.timerSettings_setting1);
settingsSetting[1]= (Spinner) dialog_settings.findViewById(R.id.timerSettings_setting2);
...
settingsItems[0].setText(R.string.settings_title1);
settingsItems[1].setText(R.string.settings_title2);
// Give some padding on left side:
for (int i = 0; i<8; i++) settingsItems[i].setPadding(10, 0, 0, 0);
// Create menu items:
final String[] items1 = new String[]{getString(R.string.settings_menu1_item1), getString(R.string.settings_menu1_item2), getString(R.string.settings_menu1_item3), getString(R.string.settings_menu1_item4)};
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items1);
settingsSetting[0].setAdapter(adapter1);
if (selectedFrag == null) settingsSetting[0].setSelection(defaultTimerSettings.OnTapResponseValue.ordinal());
else settingsSetting[0].setSelection(selectedFrag.getTapBehavior().ordinal());
<... MORE SAME CODE HERE ...>
SpinnerColorSelector mySpinnerColorSelector = new SpinnerColorSelector(this);
settingsSetting[6].setAdapter(mySpinnerColorSelector);
if (selectedFrag == null) settingsSetting[6].setSelection(findIntArraylist(mySpinnerColorSelector.colors, defaultTimerSettings.colorTimer));
else settingsSetting[6].setSelection(findIntArraylist(mySpinnerColorSelector.colors,selectedFrag.getTimerColor()));
dialog_settings.show();
Button cancelButtonOptions = (Button) dialog_settings.findViewById(R.id.buttonTimerCancelOptions);
int[] gradientColors = new int[3];
if (selectedFrag == null) gradientColors = generateGradientColors(getDefaultColor());
else gradientColors = generateGradientColors(selectedFrag.getTimerColor());
if (android.os.Build.VERSION.SDK_INT >= 16) {
GradientDrawable gdDefault = new GradientDrawable();
gdDefault.setColors(gradientColors);
gdDefault.setCornerRadius(10);
gdDefault.setStroke(1, Color.GRAY);
cancelButtonOptions.setBackground(gdDefault);
} else {
// Fallback for APIs under 16.
GradientDrawable newGdDefault = new GradientDrawable(Orientation.BOTTOM_TOP, gradientColors);
newGdDefault.setCornerRadius(10);
newGdDefault.setStroke(1, Color.GRAY);
cancelButtonOptions.setBackgroundDrawable(newGdDefault);
}
// if decline button is clicked, close the custom dialog
cancelButtonOptions.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog_settings.dismiss();
}
});
<...REMOVED TESTED CODE...>
}
// Close dialog
dialog_settings.dismiss();
//selectedFrag.setTimerValue(hour*60*60*1000+minutes*60*1000+seconds*1000);
}
});
}
catch (Exception e)
{
Log.e("MainActivityError: defaultSettingsMenu function: Error in dialog function.",Log.getStackTraceString(e));
}
}
mySpinnerColorSelector CLASS:
public class SpinnerColorSelector extends BaseAdapter {
ArrayList<Integer> colors;
Context context;
public SpinnerColorSelector(Context context)
{
this.context=context;
colors = new ArrayList<Integer>();
colors.add(Color.parseColor("#57b947")); // Time Boss green
colors.add(Color.parseColor("#33B5E5")); // Android blue
colors.add(Color.parseColor("#0099CC")); // blue
colors.add(Color.parseColor("#AA66CC")); // purple light
colors.add(Color.parseColor("#9933CC")); // purple
colors.add(Color.parseColor("#FFBB33")); // orange light
colors.add(Color.parseColor("#FF8800")); // orange
colors.add(Color.parseColor("#FF4444")); // red light
colors.add(Color.parseColor("#CC0000")); // red
}
#Override
public int getCount()
{
return colors.size();
}
#Override
public Object getItem(int arg0)
{
return colors.get(arg0);
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
#SuppressLint({ "ViewHolder", "InflateParams" }) #Override
public View getView(int pos, View view, ViewGroup parent)
{
LayoutInflater inflater=LayoutInflater.from(context);
view=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
TextView txv=(TextView)view.findViewById(android.R.id.text1);
txv.setBackgroundColor(colors.get(pos));
txv.setTextSize(20f);
txv.setTextColor(colors.get(pos));
txv.setText(colors.get(pos).toString());
return view;
}
}
LOGCAT OUTPUT:
09-24 15:14:24.631: E/AndroidRuntime(1698): FATAL EXCEPTION: main
09-24 15:14:24.631: E/AndroidRuntime(1698): Process: com.xpresspe.stopwatch, PID: 1698
09-24 15:14:24.631: E/AndroidRuntime(1698): java.lang.NullPointerException
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.TextView.makeNewLayout(TextView.java:6113)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.TextView.onMeasure(TextView.java:6408)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.Spinner.setUpChild(Spinner.java:632)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.Spinner.makeView(Spinner.java:585)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.Spinner.getBaseline(Spinner.java:431)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1089)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.forceUniformWidth(LinearLayout.java:940)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:920)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1226)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.ScrollView.onMeasure(ScrollView.java:326)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2321)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1959)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1145)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1340)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1032)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5657)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer.doFrame(Choreographer.java:544)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.os.Handler.handleCallback(Handler.java:733)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.os.Handler.dispatchMessage(Handler.java:95)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.os.Looper.loop(Looper.java:136)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.app.ActivityThread.main(ActivityThread.java:5026)
09-24 15:14:24.631: E/AndroidRuntime(1698): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 15:14:24.631: E/AndroidRuntime(1698): at java.lang.reflect.Method.invoke(Method.java:515)
09-24 15:14:24.631: E/AndroidRuntime(1698): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
09-24 15:14:24.631: E/AndroidRuntime(1698): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
09-24 15:14:24.631: E/AndroidRuntime(1698): at dalvik.system.NativeStart.main(Native Method)
Please help me...
In the SpinnerColorSelector class, I changed:
view=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
To:
view=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
And the runtime error is gone! It now runs on the emulator without problems... Still strange that try-catch didn't catch this one (maybe because the dialog is made at a later time under the hood). Anyway, back to being a happy puppy!!
This also got rid of the #SuppressLint({ "InflateParams" })