Android: java.lang.VerifyError because of a Generic Class - android

So I'm developing an Android App and I've had java.lang.VerifyError for the last couple of days. I read in a stackoverflow post that this error was due to a problem in the returns (expected return is not the one it gets).
So I believe this is due to a Generic Class that is casted into a String and I was hoping someone has a solution!
This is the generic Class:
public class ProcessJson {
public enum MessageType{
GetAppName,
GetItemsList
}
public static Object ProcessResult(MessageType messageType, String result) throws MalformedJsonException{
Gson gson = new Gson();
Object returnValue = null;
switch(messageType){
case GetAppName :
returnValue = gson.fromJson(result, String.class);
return returnValue;
case GetItemsList :
returnValue = gson.fromJson(result, Item[].class);
return returnValue;
}
return null;
}
}
Here is where I cast the class:
public void LoginBtn_OnClick(View v){
ItemAdapter adapter = (ItemAdapter)this.itemListView.getAdapter();
//Clearing the ListView
if(adapter != null) {
this.itemListView.setAdapter(null);
}
//Fetch the AplicationName
String username = this.editTextUsername.getText().toString();
String appName = RESTClient.connect("ip/DevTest/WcfApi/Api1.svc/api1/appName", username);
try {
appName = (String)ProcessJson.ProcessResult(MessageType.GetAppName, appName);
appNameTextView.setText("Logged in as: " + appName);
} catch (MalformedJsonException e) {
e.printStackTrace();
appNameTextView.setText("Cannot Login");
}
catch (JsonSyntaxException e){
e.printStackTrace();
appNameTextView.setText("Cannot Login");
}
//Fetch the itemList
String itemList = RESTClient.connect("ip/DevTest/WcfApi/Api1.svc/api1/items", username);
try{
Item[] items = (Item[])ProcessJson.ProcessResult(MessageType.GetItemsList, itemList);
//Binding itemList to UI
//ItemAdapter itemAdapter = new ItemAdapter(this, R.layout.item_row, items);
//this.itemListView.setAdapter(itemAdapter);
} catch (MalformedJsonException e) {
e.printStackTrace();
appNameTextView.setText("Cannot Login");
}
catch (JsonSyntaxException e){
e.printStackTrace();
appNameTextView.setText("Cannot Login");
}
}
I manage to avoid the crash when I put the two try/catch blocks as a comment. This is what lead me to believe the problem is due to the ProcessJson class.
Thanks in advance.

Try this workaround, it might solve your problem.

Related

how to get from MySQL data to android with json

I was tried to get data from MySQL PHP to Android with JSON Object but not work with me. I was searching about my problem but the examples I found didn't help me.
I have an array list of strings, then I set the strings MySQL DB.
After that, I want to get the cities strings from the DB with JSON, but I was unsuccessful.
My questions are:
How can I make sure that if I have city, it won't appear again?
How can I set the cities in an array list in Android?
My PHP code:
<?php
include 'connection/connection.php';
$noResult = "no results";
// to set the names at the list view
$sql = "SELECT workrCity FROM workersTable ";
$result = $connect->query($sql);
if ($result->num_rows > 0){
while($row[] = $result->fetch_assoc()) {
$json = json_encode($row,JSON_UNESCAPED_UNICODE);
}
} else {
echo $noResult;
}
echo $json;
$connect->close();
?>
the array list function in my Fragment working good :
private ArrayList<City> initCities() {
Log.d(TAG, "ArrayList_CitiesFragment_initCities");
String[] cityName = {"","","",""}; // the cities names
ArrayList<City> theCities = new ArrayList<>();
for (String aCityName : cityName) {
City city = new City(aCityName, false);
theCities.add(city);
}
return theCities;
}
Now I want to get the cities names from MySQL in a JSON-like output:
handler = new Handler(Looper.getMainLooper());
Thread runner = new Thread(new Runnable() {
#Override
public void run() {
Log.d(TAG, " runner");
GetCitiesJson getCitiesJson = new GetCitiesJson();
try{
String[] res = getCitiesJson.getCitiesDataFromDB();
JSONObject jsonObject = new JSONObject(String.valueOf(res));
JSONObject workrCity = jsonObject.getJSONObject("workrCity");
Activity activity = getActivity();
Toast.makeText(activity,"its :" + workrCity, Toast.LENGTH_SHORT).show();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
runner.start();
I know that my code is not correct, but I don't know what's missing...
Hi: Im using Volley library to get a Json file from my server and works fine and fast.
In app/build.gradle under dependencies:
compile 'com.android.volley:volley:1.0.0'
Then, in the activity you want to get the json data:
String from = "http://www.yourserver.com/file.json";
StringRequest request = new StringRequest(from, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
try {
parseJson(URLDecoder.decode(URLEncoder.encode(string, "iso8859-1"),"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Error
Log.d("ERROR:", String.valueOf(volleyError));
}
});
Volley.newRequestQueue(this).add(request);
Then you can parse the Json:
public static void parseJson(String jsonString) {
try {
JSONObject object = new JSONObject(jsonString);
getMessage(this, object);
} catch (JSONException e) {
e.printStackTrace();
}
}
And finally you can get the strings inside your Json:
public static void getMessage(JSONObject object){
if(object.length() != 0) {
try {
message = String.valueOf(object.get("message"));
} catch (JSONException e) {
e.printStackTrace();
}
} }
Okay i was copy the code. but have one problem.that the message = String.valueOf(object.get("message")); where is the var named message? it's on red colo
message is a String:String message; Then in your Json, you need a node called message to get it.

how to convert my java object to json and save it in sd card

I don't know how to do after this to convert my Java to JSON with Jackson
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper mapper = new ObjectMapper();
Book b = new Book();
ArrayList<Book> listBook = new ArrayList<Book>();
listBook.add(b);
b = new Book();
b.setName("exam");
b.setFileName("res/raw/exam.txt");
b.setCate(0); //4 categories here
b.setSoundFileName("res/raw/exams.mp3");
b.setTranFileName("res/raw/examt.txt");
listBook.add(b);
b = new Book();
b.setName("test");
b.setCate(0);
b.setFileName("res/raw/test.txt");
b.setSoundFileName("res/raw/tests.mp3")
b.setTranFileName("res/raw/textt.txt");
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(listBook);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ttt", "show ans : "+jsonString);
How do I do next to write this to my SD card?
as user Zain has told, Gson is more convenient to use, However, assuming that you are getting the Json string from this line:
jsonString = mapper.writeValueAsString(listBook);
Then use this method to write the string to a file in sdcard.
public static void writeStringToFile(String p_string, String p_fileName)
{
FileOutputStream m_stream = null;
try
{
m_stream = new FileOutputStream(p_fileName);
m_stream.write(p_string.getBytes());
m_stream.flush();
}
catch (Throwable m_th)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_th);
}
finally
{
if (m_stream != null)
{
try
{
m_stream.close();
}
catch (Throwable m_e)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_e);
}
m_stream = null;
}
}
}

How to Parse json array without any key value using objectMapper?

I am getting json response string like this.
[
"assets\/imgs\/choicelogos\/choice-logo.jpg",
"assets\/imgs\/choicelogos\/family-health-logo.jpg",
"assets\/imgs\/choicelogos\/four-corners-logo.jpg",
"assets\/imgs\/choicelogos\/grady-logo.jpg",
"assets\/imgs\/choicelogos\/hands-logo.jpg",
"assets\/imgs\/choicelogos\/morehouse-logo.jpg",
"assets\/imgs\/choicelogos\/smc-logo.jpg"
]
And this is my approach to parse this string using ObjectMapper class.
public String parseResponse(String strResponseString) {
if (MBUtil.isEmpty(strResponseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<WebAPIResponse> someClassList = objectMapper.readValue(strResponseString, typeFactory.constructCollectionType(List.class, WebAPIResponse.class));
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
But I am not able to parse. It is throwing errorMsg = null. Please any one help what I need to change?
Here is the solution of this question.
#JsonIgnoreProperties(ignoreUnknown = true)
private List<String> mWebAPIResponse;
#Override
public String parseResponse(String strResponseString) {
if (MBUtil.isEmpty(strResponseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
List<String> webAPIResponse = objectMapper.readValue(strResponseString, new TypeReference<ArrayList<String>>() {});
this.mWebAPIResponse = webAPIResponse;
} catch (Exception e) {
e.printStackTrace();
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}

Showing loading for a UI freezing async task like this one

I have an Async task class which gets the name of a web method and run it and I have to wait for the result of that web method, so I used task.execute.get() method which is freezing my UI. the problem is that I want to show a loading dialog when task is executing but when I'm trying to call this method 10 times for 10 web methods, the UI freezes and after executing 10 web methods, loading dialog appears for 1 second.
What can I do to show loading without moving all of my codes into doInBackground? I want to have a class which gets web method info and returns the result. this is my class code:
public class AsyncCallWs extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public String methodName="";
private WebService ws;
private ArrayList<ServiceParam> paramsList;
private boolean hasParams;
public AsyncCallWs(Activity activity,String methodName) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
hasParams = false;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
this.paramsList = params;
hasParams = true;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage(PersianReshape.reshape("Loading..."));
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
xLog.position();
String result = "No async task result!";
try {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
if (!hasParams){
result = ws.CallMethod(methodName);
}
else{
xLog.info("THIS METHOD IS: "+ methodName);
result = ws.CallMethod(methodName,paramsList);
xLog.info("THIS RESULT IS: "+ result);
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
xLog.position();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
xLog.info("Output of current AsyncTask is:"+ result);
}
}
And this is the way I'm calling web methods using this class:
public void doSync(String method){
xLog.position();
AsyncCallWs t;
ArrayList<ServiceParam> serviceParams = new ArrayList<ServiceParam>();
String result="";
Settings settings = new Settings(activity);
PublicVariable.pGuid = Login(settings.getValue("Username"), settings.getValue("Password"));
xLog.info("pGuid in doSync is:" + PublicVariable.pGuid);
serviceParams.add(new ServiceParam("pGuid", PublicVariable.pGuid, String.class));
if (method=="all" || method=="person"){
try {
t = new AsyncCallWs(activity,"GetPersonInfo",serviceParams);
result = t.execute().get();
xLog.info("Sync Person=>"+ result);
String fields[] = result.split(PublicVariable.FIELD_SPLITTER);
Person person = new Person(activity,fields);
person.empty();
person.insert();
settings.update("PersonId",String.valueOf(person.getId()));
PublicVariable.personId = person.getId();
xLog.info("Person inserted...");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
if (method=="all" || method=="personImage"){
try {
t = new AsyncCallWs(activity,"GetPersonImage",serviceParams);
result = t.execute().get();
if (!result.equals("Nothing")){
settings.update("picture", result);
xLog.info("Picture updatted...");
}
else
xLog.error("NO PERSON IMAGE FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="lawyers"){
try {
t = new AsyncCallWs(activity,"GetLawyers",serviceParams);
result = t.execute().get();
xLog.info("Sync Lawyer=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Lawyer lawyer= new Lawyer(activity);
lawyer.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
lawyer = new Lawyer(activity, fields);
lawyer.insert();
}
xLog.info("Lawyers inserted...");
}
else
xLog.error("NO LAWYER FOUND!");
}catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="news"){
try {
t = new AsyncCallWs(activity,"GetNews",serviceParams);
result = t.execute().get();
String fields[];
Log.d("Ehsan","Sync News=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
News news = new News(activity);
news.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
news= new News(activity,fields);
news.insert();
}
xLog.info("News inserted...");
}
else
xLog.error("NO NEWS FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="messages"){
try {
t = new AsyncCallWs(activity,"GetMessagesInbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Inbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Inbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
try {
t = new AsyncCallWs(activity,"GetMessagesOutbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Outbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Outbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="requests"){
try {
t = new AsyncCallWs(activity,"GetAllRequests",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync share buy sell requests=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Share share = new Share(activity);
share.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
share= new Share(activity,fields);
share.insert();
}
xLog.info("Shares inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="financials"){
try {
t = new AsyncCallWs(activity,"GetFinancials",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync Financials=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Financial financial = new Financial(activity);
financial.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
financial= new Financial(activity,fields);
financial.insert();
}
xLog.info("Financials inserted...");
}
else{
Log.e("Ehsan", "NOT FINANCIALS FOUND!");
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
Here
result = t.execute().get(); //<<< calling get method
as in doc AsyncTask.get() :
Waits if necessary for the computation to complete, and then retrieves
its result.
so to avoid freezing of Main UI Thread during execution of doInBackground start AsyncTask without calling get method as|:
t.execute();
I want to have a class which gets web method info and returns the
result
For this you should implement callback with AsyncTask which report to Activity. see following examples :
android asynctask sending callbacks to ui
How to implement callback with AsyncTask

how to maintain array list for new added element?

Hello every one i am working on app which is similar to the facebook.In that currently i am stuck in one point like we have posts in facebook which shows on our wall in that all the post is shows in bulk like 20 20 fashion that same thing i want to apply in my app. For that thing i use listview which get value form server and create view according to that i also get all value but the problem is that when i add 1st 20 value then it work fine but when i add another 20 value it will delete the previous data in listview.
any idea how i can do this thing in my app and thanks in advance....
my function get value from the server
private void getPostnew(String start) {
String URL = start;
System.out.println("start value new :" + start);
final String usernamefor = "";
aq = new AQuery(getParent());
listitem = new ArrayList<BeanTop>();
aq.ajax(URL, JSONObject.class, 10 * 1000,
new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json1,
AjaxStatus status) {
System.out.println("json " + json1);
if (json1 == null) {
} else {
try {
JSONArray jarray = json1
.getJSONArray("subject");
for (int j = 0; j < jarray.length(); j++) {
try {
JSONObject j1 = jarray.getJSONObject(j);
try {
listcount = j1
.getString("likecount");
} catch (Exception e) {
listcount = "0";
}
AddObject(j1.getString("text"),
j1.getString("leftpic"),
j1.getString("rightpic"),
j1.getString("rightvotecount"),
j1.getString("leftvotecount"),
j1.getString("textleft"),
j1.getString("textright"),
j1.getString("date_created"),
j1.getString("voteid"),
j1.getString("user"),
j1.getString("dom"),
j1.getString("Isvoted"),
j1.getString("Islike"),
j1.getString("profilepic"),
listcount,
j1.getString("commentcount"));
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
FriendlistAdapter ad = new FriendlistAdapter(Top.this,
listitem);
subjectlist.setAdapter(ad);
ad.notifyDataSetChanged();
}
});
}
method for save the data in bean class
private void AddObject(String string1, String string2, String string3,
String string5, String string6, String string7, String string8,
String string9, String string10, String string11,
String usernamefor, String isvoted, String isliked,
String profilepic, String likecount, String commentcount) {
BeanTop ib = new BeanTop();
Date date = null;
try {
System.out.println("date " + string9);
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string9);
} catch (Exception e) {
e.printStackTrace();
}
ib.setText(string1);
ib.setLeftpic(string2);
ib.setRightpic(string3);
ib.setRightVote(string5);
ib.setLeftVote(string6);
ib.setLefttext(string7);
ib.setRighttext(string8);
ib.setDate(string9);
ib.setDate1(date);
ib.setVoteid(string10);
ib.setUsername(string11);
ib.setDom(usernamefor);
ib.setIsvoted(isvoted);
ib.setIsliked(isliked);
ib.setProfilepic(profilepic);
ib.setLikecount(likecount);
ib.setCommentcount(commentcount);
List<BeanTop> bookingList = new ArrayList<BeanTop>();
bookingList.addAll(listitem);
Collections.sort(bookingList, new Comparator<BeanTop>() {
public int compare(BeanTop m1, BeanTop m2) {
return m1.getDate().compareTo(m2.getDate());
}
});
Collections.reverse(bookingList);
try {
listitem.clear();
} catch (Exception e) {
e.printStackTrace();
}
listitem.addAll(bookingList);
try {
bookingList.clear();
} catch (Exception e) {
e.printStackTrace();
}
listitem.add(ib);
}
Cant say without seeing your code, but I can show you general way of doing this...
First you should maintain a list, say at class level like...
List<MyPost> posts = ArrayList<MyPost>();
Then you can create you adapter by passing 'posts' list in it.
And just call '.addAll(xxx)' to you 'posts' list everytime you get items from server like,
posts.addAll(newItems);
and right after that, call yourAdapter.notifyDatasetChanged(); so that list can redraw/update its views...
And in you code...use,
if (listitem == null) {
listitem = new ArrayList<BeanTop>();
}
in you getPostnew() instead of only listitem = new ArrayList<BeanTop>();.
Hope this helps...
You are re-initializing listitem = new ArrayList<BeanTop>(); eveytime the getPostnew methood is called. This is why your old posts are lost. Try change that line to:
if (listitem == null) {
listitem = new ArrayList<BeanTop>();
}
you should use a global variable to store the data which you get from server ,in your method
getPostnew(String start) every time you execute it ,the listitem will be recreated;so the last data will be lost.

Categories

Resources