No value for JSONArray - arrays

Problem with JSONArray. This is my code, help me
This is my JsonObject and error..
Json errore: No value for {"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}{"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}
public class ListaAlunni extends AppCompatActivity {
private static ArrayList<Alunni> alunni;
AlunniListAdapter customAdapter;
private String TAG = ListaAlunni.class.getSimpleName();
private static String url = "http://192.168.1.11:80/webservice/lista.php";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_alunni);
getSupportActionBar().setTitle("Lista Alunni");
alunni = new ArrayList<Alunni>(10);
popola();
}
private void setTextLista() {
ListView ll = (ListView) findViewById(R.id.lista);
ll.setAdapter(new AlunniListAdapter(ListaAlunni.this, R.layout.lista_row, alunni));
}
private void popola() {
new AsyncTask<Object, Object, Object>() {
#Override
protected void onPreExecute() {
alunni = new ArrayList<Alunni>(10);
}
#Override
protected Object doInBackground(Object... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("Debug_object", String.valueOf(jsonObj));
// Getting JSON Array node
// try {
//JSONArray jArray=new JSONArray(jsonStr);
JSONArray jArray = jsonObj.getJSONArray(jsonStr);
Log.d("DEBUG_json", String.valueOf(jArray));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("TEST", "Username: " + json_data.getString("Username") +
", record: " + json_data.getString("Record")
);
String nome= json_data.getString("Username");
String record=json_data.getString("Record");
// alunni.add(new Alunni(nome,record));
HashMap<String, String> item = new HashMap<>();
item.put("Username", nome);
item.put("Record", record);
// adding item to item list
itemList.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json errore: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json errore: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Object o) {
setTextLista();
}
}.execute();
}
}
classe HttpHandler:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

Looking at your code, it seems JSONArray jArray = jsonObj.getJSONArray(jsonStr);
is causing the problem.
jsonObj.getJSONArray requires name of the property to be passed E.g. jsonObj.getJSONArray("array_property") but instead, it seems you are passing JSON string.
Also, before calling jsonObj.getJSONArray("array_property") you need to make sure that the array_property exists in the jsonObj

Related

JSONArray cannot be converted to JSONObject error when used as similar code

I get this error when I did the same this to my register method, I used this on my Login and it works well, but in register I get the error that the array cannot be converted to JSONObject, I am trying to put the array to convert it to JSONObject to send it to my PHP code for the database
This is my register method
private void registerUser() {
final String phone = phonenumber.getText().toString().trim();
final String lname = lastname.getText().toString().trim();
final String fname = fullname.getText().toString().trim();
final String mname = middlename.getText().toString().trim();
final String add = address.getText().toString().trim();
final String count = country.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(lname)) {
lastname.setError("Please your Last Name");
lastname.requestFocus();
return;
}
if (TextUtils.isEmpty(fname)) {
fullname.setError("Please enter your First Name");
fullname.requestFocus();
return;
}
if (TextUtils.isEmpty(add)) {
address.setError("Please enter your Address");
fullname.requestFocus();
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(Response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phone);
params.put("lastname", lname);
params.put("fullname", fname);
params.put("middleinitial", mname);
params.put("country", count);
params.put("address",add);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
this code got the error of JSON Array cannot be converted while my Login Code with the same format is working
this is my login code:
private void userLogin(){
//first getting the values
final String phonenumber = etNumber.getText().toString();
//validating inputs
if (TextUtils.isEmpty(phonenumber)) {
etNumber.setError("Please enter your Number");
etNumber.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phonenumber);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
and the error I got on my Logs is this:
W/System.err: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:168)
at org.json.JSONObject.<init>(JSONObject.java:181)
at com.example.redwallet.Register$4.onResponse(Register.java:127)
W/System.err: at com.example.redwallet.Register$4.onResponse(Register.java:120)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Extent report version 4 - Create two extent reports instead of one html report for all extectued testcases

I am using extent reportversion 4 and want one .html report after executing of all the testcases but it creates two html reports for executing the 3 methods in testclass
In the testclass, I have writteh code like that #beforemethod will execute before executing each testcase, followed by executing the testcase & in #aftermethod it will flush the repot to generate Html report and afterthat using #afterclass annotations to quit the driver**
**Testclass:**
public class HomePageTest extends BaseClass {
HomePage homePage;
public HomePageTest() {
super();
}
#BeforeMethod
#Parameters({ "platformName", "url", "udid" })
public void setUpHomePageClass(String platformName, String url, String udid) throws Exception {
try {
BaseClass baseClass = new BaseClass();
baseClass.initialize_driver(platformName, url, udid);
homePage = new HomePage(driver);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
#BeforeMethod
#Parameters({ "platformName", "url", "udid" })
public void setUpHomePageClass(String platformName, String url, String udid) throws Exception {
try {
BaseClass baseClass = new BaseClass();
baseClass.initialize_driver(platformName, url, udid);
homePage = new HomePage(driver);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Test(priority = 1, description = "Verify element i.e Top50 Txt on homepage test")
#Severity(SeverityLevel.NORMAL)
#Description("TestCase Description: Verify element i.e Top50 Txt on homepage")
public void verifyeElementsOnHomePageTest() throws Exception {
log.info("***Executing verifyElementsOnHomeScreenTest***");
logger = extent.createTest("Verify the elements on HomePage after redirecting to the splash screen");
log.info("wait for continue_button to be clickable");
TestUtil.waitForElementToBeClickable(By.id("continue_button"));
homePage.clickContinueBtnAfterSplashScreen();
log.info("Clicked on continue_button");
log.info("waitForUserNameToBeClickable - username");
boolean flag = homePage.validateTop50Txt();
Assert.assertTrue(flag);
log.info("Top50Txt isDisplayed");
log.info("verifyElementsonHomeScreenTest Ended");
}
#Test(priority = 2, description = "Swipe to next video test")
#Severity(SeverityLevel.NORMAL)
#Description("TestCase Description: Swipe from one video to another")
public void swipeToNxtVideoTest() throws InterruptedException {
try {
logger = extent.createTest("Swipe from one video to another & get the username ");
log.info("***Executing swipeToNxtVideoTest***");
log.info("waitForElementToPresenceOfElementLocated - username");
TestUtil.waitForElementToPresenceOfElementLocated(By.id("user_name"));
log.info("swipeverticalDown for nxt video");
TestUtil.swipeverticalDown();
log.info("swipeToNxtVideoTest Ended");
} catch (Exception e) {
e.printStackTrace();
log.error("Found Exception - swipeToNxtVideoTest");
}
}
/*
* #Test(priority = 3, retryAnalyzer =
* com.automation.listeners.RetryAnalyzer.class ) public void checkFailure() {
* Assert.assertEquals(true, false); System.out.println("failed");
*
* }
*/
#AfterMethod
public void getResult(ITestResult result) throws Exception {
if (result.getStatus() == ITestResult.FAILURE) {
logger.log(Status.FAIL,
MarkupHelper.createLabel(result.getName() + " - Test Case Failed", ExtentColor.RED));
logger.log(Status.FAIL,
MarkupHelper.createLabel(result.getThrowable() + " - Test Case Failed", ExtentColor.RED));
String screenshotPath = TestUtil.captureScreenAsBase64(driver, result.getName());
logger.fail("Snapshot below: " + logger.addScreenCaptureFromPath(screenshotPath));
} else if (result.getStatus() == ITestResult.SKIP) {
logger.log(Status.SKIP,
MarkupHelper.createLabel(result.getName() + " - Test Case Skipped", ExtentColor.ORANGE));
} else if (result.getStatus() == ITestResult.SUCCESS) {
logger.log(Status.PASS,
MarkupHelper.createLabel(result.getName() + " Test Case PASSED", ExtentColor.GREEN));
}
extent.flush();
}
#AfterClass
public void quitDriver() {
getDriver().quit();
}
Please do let me know where I have been lacking in code; I might have a intuitions that there is an issue in testng annotations in my code
Base Class:
DesiredCapabilities capabilities = new DesiredCapabilities();
public void setDriver(AppiumDriver<MobileElement> driver) {
tdriver.set(driver);
}
public static synchronized AppiumDriver<MobileElement> getDriver() {
return tdriver.get();
}
public BaseClass() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(
System.getProperty("user.dir") + "/src/main/java/com/automation/config/config.properties");
prop.load(ip);
// extend reports
Date date = new Date();
SimpleDateFormat dateFormatFolder = new SimpleDateFormat("dd_MMM_yyyy");
File ResultDir = new File(System.getProperty("user.dir") + File.separator + "/FrameworkReports/"
+ dateFormatFolder.format(date));
// Defining Directory/Folder Name
if (!ResultDir.exists()) { // Checks that Directory/Folder Doesn't Exists!
ResultDir.mkdir();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy_hh_mm_ssaa");
htmlReporter = new ExtentHtmlReporter(
ResultDir + "/" + "Report" + " " + dateFormat.format(date) + " .html");
htmlReporter.config().setDocumentTitle("Automation Report");
htmlReporter.config().setReportName("YOVO AUTOMATION");
htmlReporter.config().setTheme(Theme.DARK);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("Host Name", "localhost");
extent.setSystemInfo("Environment", "Windows 7");
extent.setSystemInfo("User Name", "Abhishek Chauhan");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void initialize_driver(String platformName, String url, String udid) throws Exception {
log = LogManager.getLogger(BaseClass.class);
BasicConfigurator.configure();
File appDir = new File("/src/main/resources/apk");
File app = new File(appDir, "yovoapp-release.apk");
mDirpath = System.getProperty("user.dir");
mApkfilepath = mDirpath + "/app/yovoapp-release.apk";
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, platformName);
capabilities.setCapability(MobileCapabilityType.UDID, udid);
switch (platformName) {
case "Android":
capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60);
capabilities.setCapability("appPackage", prop.getProperty("androidAppPackage"));
capabilities.setCapability("appActivity", prop.getProperty("androidAppActivity"));
capabilities.setCapability("app", mApkfilepath);
capabilities.setCapability("noReset", true);
driver = new AppiumDriver<MobileElement>(new URL(url), capabilities);
// tdriver.set(driver);
// return getDriver();
case "IOS":
File classpathRoot = new File(System.getProperty("user.dir"));
// File appDir = new File(classpathRoot, "/build/");
// File app = new File(appDir, "WordPress.app");
capabilities.setCapability("platformVersion", "9.2");
capabilities.setCapability("deviceName", "iPhone 6");
capabilities.setCapability("app", app.getAbsolutePath());
// driver = new IOSDriver<MobileElement>(new
// URL("http://127.0.0.1:4723/wd/hub"), caps);
break;
default:
throw new Exception("Invalid platform! - " + platformName);
}
setDriver(driver);
}

cn1 - Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference

I've a error thrown I can't figure out how it happens. It doesn't occur all the time but once in a while. The error message thrown is "Java.lang.nullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference". I've used connectionRequest for parsing the json data. When the error is thrown I've checked if there's problem in url but it gives the proper json data as always. After trying few times, the error is solved automatically.
if (!regNOField.getText().equals("") && !newPasswordField.getText().equals("")) {
ArrayList<Map<String, String>> argumentsArrayList = new ArrayList<>();
Map argumentMap1 = new HashMap();
argumentMap1.put("argument", "reg_no");
argumentMap1.put("value", regNOField.getText().trim());
argumentsArrayList.add(argumentMap1);
Map argumentMap2 = new HashMap();
argumentMap2.put("argument", "token");
argumentMap2.put("value", newPasswordField.getText().trim());
argumentsArrayList.add(argumentMap2);
CommonMethod.connectionMethod(res, true, url, "Verification", argumentsArrayList, true, null);
}
CommonMethod.connectionMethod:
public static void connectionMethod(Resources res, Boolean postBoolean, String urlString, String form, ArrayList<Map<String, String>> arguments,
Boolean ipFlag, String extraData) {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jp = new JSONParser();
parser = jp.parseJSON(new InputStreamReader(input));
response = null;
if (parser != null && !parser.isEmpty()) {
if (parser.get("status").equals("true")) {
message = (String) parser.get("data");
ToastBar.getInstance().setPosition(Component.TOP);
ToastBar.showErrorMessage(message, 5000);
if (form.equals("Verification")) {
if (d != null) {
d.dispose();
}
new LoginAndSignUp(res, message).show();
}
}
}
}
#Override
protected void handleErrorResponseCode(int code, String message) {
System.out.println("login ErrorResponseCode " + code + "msg: " + message);
}
#Override
protected void handleException(Exception err) {
System.out.println("login Exception " + err);
}
#Override
protected void handleIOException(IOException err) {
System.out.println("login IOException " + err);
}
#Override
protected void handleRuntimeException(RuntimeException err) {
System.out.println("RuntimeException " + err);
}
};
cr.setPost(postBoolean);
cr.setUrl(urlString);
cr.setTimeout(80000);
if (arguments != null && !postBoolean.equals(false)) {
for (Map<String, String> entrySet : arguments) {
String argument1 = (String) entrySet.get("argument");
String value1 = (String) entrySet.get("value");
cr.addArgument(argument1, value1);
}
}
InfiniteProgress ip = new InfiniteProgress();
d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d);
cr.addRequestHeader("accept", "application/json");
NetworkManager.getInstance().addToQueueAndWait(cr);
}
Error msg:

Codenameone closing a socket

There seems to be no way of disconnecting a socket without causing a connection reset error on the server side.
I'm using the com.codename1.io.Socket and com.codename1.io.SocketConnection implementations within a tester app. My code is as follows:
private SpanLabel lblStatus;
private SpanLabel lblIncoming;
private CustomSocketConnection con;
private Thread tIncoming;
public ConnectForm() {
con = getSocketConnection();
Button btnConnect = getConnectButton();
Button btnDisconnect = getDisconnectButton();
Button btnSendMessage = getSendMessageButton();
lblStatus = getInfoLabel();
lblIncoming = getIncomingLabel();
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
addComponent(btnConnect);
addComponent(btnDisconnect);
addComponent(btnSendMessage);
addComponent(lblStatus);
addComponent(lblIncoming);
}
private Button getConnectButton() {
Button btn = new Button("Connect (localhost)");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Socket.connect("localhost", 8687, con);
}
});
return btn;
}
private Button getDisconnectButton() {
Button btn = new Button("Disconnect");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//??? I don't know how to do this
try {
tIncoming.join();
} catch (Exception e) {
e.printStackTrace();
tIncoming.interrupt();
}
}
});
return btn;
}
private Button getSendMessageButton() {
Button btn = new Button("Send Message");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
con.os.write("Hello".getBytes());
con.os.write(Integer.parseInt("04", 16)); //end of transmit
con.os.flush();
lblStatus.setText("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return btn;
}
private SpanLabel getInfoLabel() {
return new SpanLabel("Disconnected");
}
private SpanLabel getIncomingLabel() {
return new SpanLabel("...");
}
private CustomSocketConnection getSocketConnection() {
return new CustomSocketConnection();
}
class CustomSocketConnection extends SocketConnection {
public OutputStream os;
public InputStream is;
#Override
public void connectionError(int errorCode, String message) {
lblStatus.setText("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
lblStatus.setText("Connected :)");
this.is = is;
this.os = os;
spawnIncomingMessageWatcher();
}
}
private void spawnIncomingMessageWatcher() {
tIncoming = new Thread(new Runnable() {
public void run() {
String s = "";
int eot = Integer.parseInt("04", 16);
while (con.isConnected()) {
try {
int temp;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (((temp = con.is.read()) != -1) && (temp != eot)) {
baos.write(temp);
}
lblIncoming.setText(new String(baos.toByteArray()));
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tIncoming.start();
}
With the getDisconnectButton() method, I do not know how to properly disconnect from the server, as the SocketConnection object does not seem to have an appropriate method for this.
If you call close() on either the Input- or OutputStream then you close the Socket, code from Socket.SocketInputStream class link.
public void close() throws IOException {
closed = true;
if(Util.getImplementation().isSocketConnected(impl)) {
Util.getImplementation().disconnectSocket(impl);
con.setConnected(false);
}
}
So first send close instruction to Server and then close a stream.
Hope this helps,

data/data/com.package/databases folder isn't showed

I made an android dictionary application. I have created a database named "kamusJawa.sqlite" and copied it to the assets folder. I tried the code in this link Own Database in Assets Folder on Android Eclipse Project
This is my database manager class:
package com.kamusJI;
public class DBHelper extends SQLiteOpenHelper{
private static String DBPATH = "/data/data/com.kamusJI/databases/";
private static String DBNAME = "kamusJawa.sqlite";
private SQLiteDatabase DBSQ;
private final Context KJICtx;
public DBHelper(Context context) throws IOException {
super(context, DBNAME, null, 1);
this.KJICtx = context;
// TODO Auto-generated constructor stub
boolean dbexist = cekDB();
if (dbexist) {
//System.out.println("Database exists");
openDB();
} else {
System.out.println("Database doesn't exist");
createDB();
}
}
public void createDB() throws IOException{
boolean dbExist = cekDB();
if(!dbExist){
this.getReadableDatabase();
try{
salinDB();
}catch (IOException e){
throw new Error("Gagal menyalin database");
}
}
}
boolean cekDB() {
//SQLiteDatabase cekDatabase = null;
boolean cekdb = false;
try{
String path = DBPATH + DBNAME;
File dbfile = new File(path);
//cekDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
cekdb = dbfile.exists();
}catch(SQLException e){
System.out.println("Database tidak ada");
}
return cekdb;
//return cekDatabase !=null ? true : false;
}
private void salinDB() throws IOException{
AssetManager AM = KJICtx.getAssets();
File DbFile = new File(DBPATH+DBNAME);
InputStream in = KJICtx.getAssets().open(DBNAME);
//OutputStream out = new FileOutputStream(DbFile);
OutputStream out = new FileOutputStream("/data/data/com.kamusJI/databases/kamusJawa.sqlite");
DbFile.createNewFile();
byte[] b = new byte[1024];
int i, r;
String[] Files = AM.list("");
Arrays.sort(Files);
i= 1;
String fdb = String.format("kamusJawa.db.00%d", i);
while(Arrays.binarySearch(Files, fdb)>=0){
//InputStream in = AM.open(fdb);
while(( r = in.read(b))>0)
out.write(b,0,r);
in.close();
i++;
fdb = String.format("kamusJawa.db.00%d", i);
}
out.flush();
out.close();
}
public void openDB() throws SQLException{
String path = DBPATH+DBNAME;
DBSQ = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(DBSQ !=null)
DBSQ.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
and this is my main class:
package com.kamusJI;
public class KJI extends ListActivity {
private KJI this_class = this;
String[] Menu = {"Basa Jawa", "Bahasa Indonesia", "Tambah Data"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.Cari, Menu));
ListView lv = getListView();
lv.setTextFilterEnabled(false);
/* Defines On Item Click callback method */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent action = null;
switch(position) {
case 0:
case 1:
action = new Intent(getApplicationContext(), Cari.class);
action.putExtra("MODE", position);
break;
case 2:
action = new Intent(getApplicationContext(), Tambah.class);
action.putExtra("MODE", position);
break;
case 3:
finish();
return;
}
startActivity(action);
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void InitDatabase() {
AsyncTask<String, Void, String> InitDB = new AsyncTask<String, Void, String>() {
Dialog progress = null;
String msg;
DBHelper dbhelper;
#Override
protected void onPreExecute() {
try {
dbhelper = new DBHelper(this_class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!dbhelper.cekDB())
progress = ProgressDialog.show(this_class, "", "Installing Database.\nPlease wait.");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
dbhelper.createDB();
msg = "Database successfully installed.";
} catch (IOException ioe) {
msg = "Database installation failed.";
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progress!=null) {
progress.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
};
InitDB.execute(new String());
}
}
When I run my application, then I go to file explorer, I can't find the data/data/com.kamusJI/databases. How it can be like that?
change your database name extension to .db
You need special permissions like root access to read the path:
/data/data/com.package/databases

Resources