Download large files using large byte array causes "Out of memory" - java

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);
}

Related

Fragment cannot be cast to android.content.Context

I want to connect my login page to MySQL PHP but I got some error here.
This is my logcat:
807/com.aeu.mlibrary.mlibraryaeu E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aeu.mlibrary.mlibraryaeu, PID: 1807
java.lang.ClassCastException: com.aeu.mlibrary.mlibraryaeu.LoginFragment cannot be cast to android.content.Context
at com.kosalgeek.asynctask.PostResponseAsyncTask.<init>(PostResponseAsyncTask.java:284)
at com.aeu.mlibrary.mlibraryaeu.LoginFragment.onClick(LoginFragment.java:82)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
and this is the error line in my loginFragment.java:
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("mobile", "android");
postData.put("txtUsername", etUsername.getText().toString());
postData.put("txtPassword", etPassword.getText().toString());
PostResponseAsyncTask task = new PostResponseAsyncTask(LoginFragment.this, postData);
task.execute("http://10.0.3.2/mlibrary/HTML/login.php");
}
I need your help guys!
Thank you.
Replace LoginFragment.this with getActvity()
PostResponseAsyncTask task = new PostResponseAsyncTask(getActivity(), postData);
Replace LoginFragment.this with getContext() :
PostResponseAsyncTask task = new PostResponseAsyncTask(getContext(), postData);

Can't connect on service and get JSON

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;
}

read txt file into 2d array force exit

firstly i am sorry for my broken english. I wanna read txt file and into 2d array. this code is succesfully running on java. but android emulator gives warning message: "Sorry! the application has stopped unexpectedly. please try again"
how can I fix that? thanks
here is my code:
package com.example.hocam;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Konular extends ActionBarActivity {
private ListView konuListe;
private List<KonuBilgileri> konuBilgileri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_konular);
Bundle dersadi = getIntent().getExtras();
String dersinadi= dersadi.getString("Ders");
switch(dersinadi) {
case "Turkce":
KonuGetir turkce=new KonuGetir("turkce.txt");
String[][] turkcekonular=turkce.getKonular();
System.out.println(turkcekonular[0][0]); // it is the problem and give error
konuListe = (ListView) findViewById(R.id.konu_listesi);
konuBilgileri = new ArrayList<KonuBilgileri>();
konuBilgileri.add(new KonuBilgileri(turkcekonular[0][0],R.drawable.turkce, turkcekonular[0][1])); // array is problem
MyAdapter adapter = new MyAdapter(Konular.this, R.layout.custom_list_item, konuBilgileri);
konuListe.setAdapter(adapter);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.konular, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class KonuGetir {
final int maxLines = 10100;
String[][] resultArray = new String[maxLines][];
public KonuGetir(String Ders){
File file = new File(Ders);
Scanner scanner;
try {
scanner = new Scanner(file,"utf-8");
int linesCounter = 0;
while (scanner.hasNextLine() && linesCounter < maxLines) {
resultArray[linesCounter] = scanner.nextLine().split("#");
linesCounter++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String[][] getKonular() {
return resultArray;
}
}
logfile:
> 09-04 16:18:22.262: E/AndroidRuntime(1164): FATAL EXCEPTION: main
09-04 16:18:22.262: E/AndroidRuntime(1164): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hocam/com.example.hocam.Konular}: java.lang.NullPointerException
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.os.Looper.loop(Looper.java:123)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 16:18:22.262: E/AndroidRuntime(1164): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 16:18:22.262: E/AndroidRuntime(1164): at java.lang.reflect.Method.invoke(Method.java:521)
09-04 16:18:22.262: E/AndroidRuntime(1164): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 16:18:22.262: E/AndroidRuntime(1164): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 16:18:22.262: E/AndroidRuntime(1164): at dalvik.system.NativeStart.main(Native Method)
09-04 16:18:22.262: E/AndroidRuntime(1164): Caused by: java.lang.NullPointerException
09-04 16:18:22.262: E/AndroidRuntime(1164): at com.example.hocam.Konular.onCreate(Konular.java:66)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-04 16:18:22.262: E/AndroidRuntime(1164): ... 11 more
09-04 16:42:10.422: E/AndroidRuntime(1178): FATAL EXCEPTION: main
09-04 16:42:10.422: E/AndroidRuntime(1178): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hocam/com.example.hocam.Konular}: java.lang.NullPointerException
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.os.Looper.loop(Looper.java:123)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 16:42:10.422: E/AndroidRuntime(1178): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 16:42:10.422: E/AndroidRuntime(1178): at java.lang.reflect.Method.invoke(Method.java:521)
09-04 16:42:10.422: E/AndroidRuntime(1178): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 16:42:10.422: E/AndroidRuntime(1178): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 16:42:10.422: E/AndroidRuntime(1178): at dalvik.system.NativeStart.main(Native Method)
09-04 16:42:10.422: E/AndroidRuntime(1178): Caused by: java.lang.NullPointerException
09-04 16:42:10.422: E/AndroidRuntime(1178): at com.example.hocam.Konular.onCreate(Konular.java:66)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-04 16:42:10.422: E/AndroidRuntime(1178): ... 11 more
09-04 16:43:28.802: E/AndroidRuntime(1207): FATAL EXCEPTION: main
09-04 16:43:28.802: E/AndroidRuntime(1207): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hocam/com.example.hocam.Konular}: java.lang.NullPointerException
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.os.Looper.loop(Looper.java:123)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 16:43:28.802: E/AndroidRuntime(1207): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 16:43:28.802: E/AndroidRuntime(1207): at java.lang.reflect.Method.invoke(Method.java:521)
09-04 16:43:28.802: E/AndroidRuntime(1207): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 16:43:28.802: E/AndroidRuntime(1207): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 16:43:28.802: E/AndroidRuntime(1207): at dalvik.system.NativeStart.main(Native Method)
09-04 16:43:28.802: E/AndroidRuntime(1207): Caused by: java.lang.NullPointerException
09-04 16:43:28.802: E/AndroidRuntime(1207): at com.example.hocam.Konular.onCreate(Konular.java:66)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-04 16:43:28.802: E/AndroidRuntime(1207): ... 11 more
android manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".YGS"
android:label="#string/title_activity_ygs" >
</activity>
<activity
android:name=".Konular"
android:label="#string/title_activity_konular" >
</activity>
<activity
android:name=".Video"
android:screenOrientation="landscape"
android:label="#string/title_activity_video" >
</activity>
</application>
You are using the following code:
String[][] turkcekonular=turkce.getKonular();
System.out.println(turkcekonular[0][0]);
But get java.lang.NullPointerException.
The reason for this because getKonular() returns an array initalised to size 10100, however scanner does not contain any lines so scanner.hasNextLine() is false.
This means that turkcekonular[0] is null, as it was never set.
Which means that turkcekonular[0][0] is trying to access a null object, so throws a NullPointerException
You should check if the object is null before trying to access it..
if(turkcekonular[0] != null)
System.out.println(turkcekonular[0][0]);
and else where that this issue occurs.
(and you should figure out why your file is not read. Is it named correctly and exists in the specified path?)

Must implement the interface while implemented this interface in a activity

I have a Main activity. at Main Activity, in Oncreat{}, i creat a fragment with name "ChannelList"
Code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initVtcId();
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentById(android.R.id.tabcontent) == null) {
FragmentTransaction fragmentTransaction = fm.beginTransaction();
ChannelList list = new ChannelList();
//fragmentTransaction.add(android.R.id.content, list);
fragmentTransaction.add(android.R.id.tabcontent, list);
fragmentTransaction.commit();
}
To oder to ChannelList to communicate up to a Activity with name "ChannelActivity". I use a Interface with name "OnListItemSelectedListener " and its method "onListItemSelected" in ChannelList
public class ChannelList extends ListFragment {
private OnListItemSelectedListener mCallback;
public interface OnListItemSelectedListener {
public void onListItemSelected(ListView l, int position);
}
The Fragment ChannelList captures the interface implementation during its onAttach() lifecycle method
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnListItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemSelectedListener");
}
}
the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
public void onListItemClick(ListView l, View v, int position, long id) {
mCallback.onListItemSelected(l, mChannelAdapter.getItem(position)
.getID());
}
On ChannelActivity, I implement this interface and its method to call a Fragment with name "ChannelDetailFragment"
public class ChannelActivity extends FragmentActivity implements
ChannelList.OnListItemSelectedListener {
private FragmentManager fm;
private Fragment mChannelDetailFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.channel_activity);
fm = getSupportFragmentManager();
Fragment mChannelListFragment = fm
.findFragmentByTag(ChannelList.TAG);
if (mChannelListFragment == null) {
addFragment(new ChannelList(), false,
ChannelList.TAG);
}
}
#Override
public void onListItemSelected(ListView l, int position) {
Bundle args = new Bundle();
args.putInt(ChannelDetailFragment.CHANNEL_ID, position);
mChannelDetailFragment = fm
.findFragmentByTag(ChannelDetailFragment.TAG);
if (mChannelDetailFragment == null) {
mChannelDetailFragment = new ChannelDetailFragment();
}
mChannelDetailFragment.setArguments(args);
addFragment(mChannelDetailFragment, true, ChannelDetailFragment.TAG);
}
I follow this tut at:
http://developer.android.com/training/basics/fragments/communicating.html#Deliver
Unfortunately, I have an error throw from OnAttach{}. I checked my code manytimes but not detect where is incorrect. Sb help me!
10-02 14:07:40.156: E/AndroidRuntime(980): FATAL EXCEPTION: main
10-02 14:07:40.156: E/AndroidRuntime(980): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.channellistfragment/com.example.channellistfragment.MainActivity}: java.lang.ClassCastException: com.example.channellistfragment.MainActivity#a68d01b8 must implement OnListItemSelectedListener
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.os.Handler.dispatchMessage(Handler.java:99)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.os.Looper.loop(Looper.java:137)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-02 14:07:40.156: E/AndroidRuntime(980): at java.lang.reflect.Method.invokeNative(Native Method)
10-02 14:07:40.156: E/AndroidRuntime(980): at java.lang.reflect.Method.invoke(Method.java:511)
10-02 14:07:40.156: E/AndroidRuntime(980): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-02 14:07:40.156: E/AndroidRuntime(980): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-02 14:07:40.156: E/AndroidRuntime(980): at dalvik.system.NativeStart.main(Native Method)
10-02 14:07:40.156: E/AndroidRuntime(980): Caused by: java.lang.ClassCastException: com.example.channellistfragment.MainActivity#a68d01b8 must implement OnListItemSelectedListener
10-02 14:07:40.156: E/AndroidRuntime(980): at com.example.channellistfragment.ChannelList.onAttach(ChannelList.java:79)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:867)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.Activity.performStart(Activity.java:5018)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
10-02 14:07:40.156: E/AndroidRuntime(980): ... 11 more
You have 2 activities and add ChannelList fragment to both of them. First one (Main Activity) doesnt implements your callback interface and you get ClassCast exeption.

java.lang.ClassCastException: org.ksoap2.serialization.SoapObject in android

Hi i have developed one android application.
The app purpose is retrieve data from mysql database and display in android device.
This is my android code:
public class RetailerActivity extends Activity {
private final String NAMESPACE = "http://ws.testprops.com";
private final String URL = "http://krish.jelastic.servint.net/Retrieve/services/Fetch?wsdl";
private final String SOAP_ACTION = "http://ws.testprops.com/customerData";
private final String METHOD_NAME = "customerData";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
try {
ht.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
SoapPrimitive s = response;
String str = s.toString();
String resultArr[] = str.split("&");//Result string will split & store in an array
TextView tv = new TextView(this);
for(int i = 0; i<resultArr.length;i++){
tv.append(resultArr[i]+"\n\n");
}
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}}
If i have to run the app means blank screen only displayed.it is taking too long time nearly 1 hour
also am getting following error on my android console window:
11-05 10:38:27.868: W/System.err(837): java.lang.ClassCastException: org.ksoap2.serialization.SoapObject
11-05 10:38:27.878: W/System.err(837): at com.retailer.client.RetailerActivity.onCreate(RetailerActivity.java:29)
11-05 10:38:27.878: W/System.err(837): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-05 10:38:27.878: W/System.err(837): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-05 10:38:27.878: W/System.err(837): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-05 10:38:27.878: W/System.err(837): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-05 10:38:27.878: W/System.err(837): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-05 10:38:27.878: W/System.err(837): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 10:38:27.878: W/System.err(837): at android.os.Looper.loop(Looper.java:123)
11-05 10:38:27.878: W/System.err(837): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-05 10:38:27.878: W/System.err(837): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 10:38:27.878: W/System.err(837): at java.lang.reflect.Method.invoke(Method.java:521)
11-05 10:38:27.878: W/System.err(837): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-05 10:38:27.878: W/System.err(837): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-05 10:38:27.888: W/System.err(837): at dalvik.system.NativeStart.main(Native Method)
please help me.how can i resolve this error.
Change
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
to
SoapObject response = (SoapObject)envelope.getResponse();

Categories