2015-09-10 177 views
0

使用asyntask查询表中的所有数据并将其放入数组List中,然后将其发送到服务器时,出现问题。我能够将数据成功发送到服务器。但是应用程序崩溃的异步服务器的postexecute给出以下错误:AsyncTask postExecute崩溃

(W/System.err﹕ org.json.JSONException: Value ["com[email protected]41b06d18","com[email protected]41b070b8"] of type org.json.JSONArray cannot be converted to JSONObject).. 

什么可能是问题?我在哪里错了。有人请帮助...非常感谢。

package com.practical.tasks.school; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.NotificationManager; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.graphics.Color; 
import android.graphics.drawable.ColorDrawable; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.ListView; 
import android.widget.Toast; 

import org.apache.http.Header; 
import org.apache.http.HttpResponse; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.auth.BasicScheme; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.protocol.HTTP; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

@SuppressWarnings("deprecation") 
public class SyncMembersActivity extends ActionBarActivity { 
CustomHttpClient jParser = new CustomHttpClient(); 
ListView lstView; 
public MainDB dbs; 
public SQLiteDatabase db; 
public static String fname; 
String username = "atlantis"; 
String password = "@[email protected]"; 
Button submit; 
String statusN = "NO"; 
String statusY = "YES"; 
String url = "http://123.456.78.90:1234/Api/create/Post"; 
String FirstName = ""; 
String SecondName = ""; 
String MobileNumber = ""; 
String DateofBirth = ""; 
String Gender = ""; 
String GroupName = ""; 
String GroupAccountNo = ""; 
String IdentificationID = ""; 
String IdentificationType = null; 
String CreatedBy = null; 
String Residence = ""; 
private int notificationIdOne = 111; 
private int numMessagesOne = 0; 
private NotificationManager myNotificationManager; 
String account_statusY = "True"; 
private ProgressDialog prgDialog; 


private ArrayAdapter<String> listAdapter; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sync_members); 

    getSupportActionBar().setHomeButtonEnabled(true); 
    getSupportActionBar().setDisplayShowHomeEnabled(true); 
    getSupportActionBar().setHomeActionContentDescription("Services"); 
    getSupportActionBar().setDisplayUseLogoEnabled(true); 
    getSupportActionBar().setLogo(R.mipmap.ic_launcher); 
    getSupportActionBar().setDisplayShowTitleEnabled(true); 
    getSupportActionBar().setBackgroundDrawable(new   ColorDrawable(Color.parseColor("#5A92F7"))); 

    lstView = (ListView) findViewById(R.id.lstSample); 
    submit = (Button) findViewById(R.id.upload); 

    prgDialog = new ProgressDialog(this); 
    prgDialog.setMessage("Please wait..."); 
    prgDialog.setCancelable(false); 


    submit.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      try { 

       if (isNetworkAvailable(getApplicationContext())) { 

        new HttpAsyncTask().execute(FirstName, SecondName, MobileNumber, DateofBirth, Gender, GroupName, GroupAccountNo, IdentificationID, IdentificationType, CreatedBy, Residence); 

       } else { 
        showAlert("No internet Connectivity..."); 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    }); 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.menu_sync_members, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

public class MemberRecords { 

    String FirstName; 
    String SecondName; 
    String MobileNumber; 
    String DateofBirth; 
    String Gender; 
    String GroupName; 
    String GroupAccountNo; 
    String IdentificationID; 
    String IdentificationType; 
    String CreatedBy; 
    String Residence; 

    public String getFirstName() { 
     return FirstName; 
    } 

    public String getSecondName() { 
     return SecondName; 
    } 

    public String getMobileNumber() { 
     return MobileNumber; 
    } 

    public String getDateofBirth() { 
     return DateofBirth; 
    } 

    public String getGender() { 
     return Gender; 
    } 

    public String getGroupName() { 
     return GroupName; 
    } 

    public String getGroupAccountNo() { 
     return GroupAccountNo; 
    } 

    public String getIdentificationID() { 
     return IdentificationID; 
    } 

    public String getIdentificationType() { 
     return IdentificationType; 
    } 

    public String getCreatedBy() { 
     return CreatedBy; 
    } 

    public String getResidence() { 
     return Residence; 
    } 


    public void setFirstName(String newfirstName) { 
     FirstName = newfirstName; 
    } 

    public void setSecondName(String newSecondName) { 
     SecondName = newSecondName; 
    } 

    public void setMobileNumber(String mobileNumber) { 
     MobileNumber = mobileNumber; 
    } 

    public void setDateofBirth(String dateofBirth) { 
     DateofBirth = dateofBirth; 
    } 

    public void setGender(String gender) { 
     Gender = gender; 
    } 

    public void setGroupName(String groupName) { 
     GroupName = groupName; 
    } 

    public void setGroupAccountNo(String groupAccountNo) { 
     GroupAccountNo = groupAccountNo; 
    } 

    public void setIdentificationID(String identificationID) { 
     IdentificationID = identificationID; 
    } 

    public void setIdentificationType(String identificationType) { 
     IdentificationType = identificationType; 
    } 

    public void setCreatedBy(String createdBy) { 
     CreatedBy = createdBy; 
    } 

    public void setResidence(String residence) { 
     Residence = residence; 
    } 

} 

public boolean isConnected() { 
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) 
     return true; 
    else 
     return false; 
} 

public static String POST(String url, MemberRecords my) { 
    InputStream inputStream; 
    String result = ""; 
    String username = "atlantis"; 
    String password = "@[email protected]"; 
    Integer n; 

    try { 

     // 1. create HttpClient 
     HttpClient httpclient = new DefaultHttpClient(); 

     // 2. make POST request to the given URL 
     HttpPost httpPost = new HttpPost("http://41.186.47.26:4433/Api/Account/PostAddSignatory"); 

     String json = ""; 
     Log.e("Url", "Url Here:" + url); 


     // 3. build jsonObject 
     JSONObject jsonObject = new JSONObject(); 
     jsonObject.accumulate("FirstName", my.getFirstName()); 
     jsonObject.accumulate("SecondName", my.getSecondName()); 
     jsonObject.accumulate("MobileNumber", my.getMobileNumber()); 
     jsonObject.accumulate("DateofBirth", my.getDateofBirth()); 
     jsonObject.accumulate("Gender", my.getGender()); 
     jsonObject.accumulate("GroupName", my.getGroupName()); 
     jsonObject.accumulate("GroupAccountNo", my.getGroupAccountNo()); 
     jsonObject.accumulate("IdentificationID", my.getIdentificationID()); 
     jsonObject.accumulate("IdentificationType", my.getIdentificationType()); 
     jsonObject.accumulate("CreatedBy", my.getCreatedBy()); 
     jsonObject.accumulate("Residence", my.getResidence()); 

     json = jsonObject.toString(); 

     Log.e("Url", "Request:" + json); 

     StringEntity se = new StringEntity(json); 

     httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); 
     UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); 
     Header header = new BasicScheme().authenticate(credentials, httpPost); 
     httpPost.addHeader(header); 
     httpPost.setEntity(se); 

     HttpResponse httpResponse = httpclient.execute(httpPost); 

     inputStream = httpResponse.getEntity().getContent(); 

     if (inputStream != null) 
      result = convertInputStreamToString(inputStream); 


     else 
      result = "Did not work!"; 

    } catch (Exception e) { 
     Log.e("InputStream", e.getLocalizedMessage()); 
     //e.printStackTrace(); 
    } 

    // 11. return result 
    return result; 
} 

private static String convertInputStreamToString(InputStream inputStream) throws IOException, JSONException { 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
    String line = ""; 
    String result = ""; 


    while ((line = bufferedReader.readLine()) != null) 
     result += line; 


    Log.e("Url", "Response:" + result); 

    inputStream.close(); 
    return result; 

} 

private class HttpAsyncTask extends AsyncTask<String, Void,String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     prgDialog.show(); 
    } 


    @Override 
    protected String doInBackground(String... urls) { 
     dbs = new MainDB(SyncMembersActivity.this); 
     db = dbs.getWritableDatabase(); 
     Integer n=null; 

     MemberRecords my = new MemberRecords(); 
     List<MemberRecords> member_list = new ArrayList<>(); 
     try { 

      Cursor cursor = db.rawQuery("SELECT * FROM tbl_memberData" + 
        " where sync_status = '" + statusN + "' AND account_status = '" + account_statusY + "'", null); 
      if (cursor.moveToFirst()) { 
       do { 
        my = new MemberRecords(); 
        my.setGroupName(cursor.getString(1)); 
        my.setIdentificationID(cursor.getString(2)); 
        my.setIdentificationType(cursor.getString(3)); 
        my.setFirstName(cursor.getString(4)); 
        my.setSecondName(cursor.getString(5)); 
        my.setDateofBirth(cursor.getString(6)); 
        my.setMobileNumber(cursor.getString(7)); 
        my.setGender(cursor.getString(8)); 
        my.setGroupAccountNo(cursor.getString(9)); 
        my.setCreatedBy(cursor.getString(10)); 
        my.setResidence(cursor.getString(11)); 

        member_list.add(my); 

       } while (cursor.moveToNext()); 
      } 

      cursor.close(); 

     } catch (NumberFormatException e) { 
      e.printStackTrace(); 
     } 

     for (n = 0; n < member_list.size(); n++) { 
      POST(url, member_list.get(n)); 
     } 
     db.close(); 
     return String.valueOf(member_list); 
    } 

    //onPostExecute displays the results of the AsyncTask. 
    //Response format 
    //Response:{"ResponseCode":"00","ResponseMsg":"Successful"} 
    //Response:{"ResponseCode":"01","ResponseMsg":"Failed"} 
     @Override 
     protected void onPostExecute (String result){ 
      prgDialog.dismiss(); 

      Toast.makeText(getBaseContext(),"Saved Successfully",Toast.LENGTH_LONG).show(); 
      dbs = new MainDB(SyncMembersActivity.this); 
      db = dbs.getWritableDatabase(); 
      String updateQuery = "Update tbl_memberData set sync_status = '" + statusY + "' where account_status='" + account_statusY + "'"; 
      db.execSQL(updateQuery); 

      String success=""; 
      String message=""; 

      try { 
       JSONObject jsonBreaker = new JSONObject(result); 
       success = jsonBreaker.getString("ResponseCode"); 
       message = jsonBreaker.getString("ResponseMsg"); 


       if (success.equalsIgnoreCase("00")) { 


        prgDialog.dismiss(); 

        showAlert(message); 


       } else if (success.equalsIgnoreCase("01")) { 

        prgDialog.dismiss(); 
        //do 
        showAlert(message); 

       } else { 

        prgDialog.dismiss(); 

        Toast.makeText(getBaseContext(), "Error, Please try again...", Toast.LENGTH_LONG).show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     } 


    } 


    private void showAlert(String message) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage(message).setTitle("Response from Server") 
       .setCancelable(false) 
       .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         // do nothing 
        } 
       }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 


    public boolean isNetworkAvailable(final Context context) { 
     final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)); 
     return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected(); 
    } 

} 
+0

可能是什么问题?您正在以错误的方式构建某种JSON数据 - 这就是例外情况。如果您可以发布堆栈跟踪并指出引发异常的位置 – Antoniossss

+0

尊敬的团队,......我收到来自服务器的响应,作为JSON响应。这是我收到的响应:----响应:{“ ResponseCode “:” 00" , “ResponseMsg”: “成功”}。当我尝试从SQLite中查询所有数据并将其放入一个ListArray并一次发送通过asyncTask时,会发生此问题.......但是,当我只查询一个项目并发送时,不会发生此错误 – Turbo

+0

当它到达JSONObject时发生错误jsonBreaker = new JSONObject(result);我希望这些信息对您有所帮助。我真的被困在这里。 – Turbo

回答

0

如果你想basta stacktrace和opoint其中rxception被抛出会更容易。 反正

result可能是和JSONArray不是JSONObject所以这

JSONObject jsonBreaker = new JSONObject(result); 

导致异常。构建JSONArray保证JSONObject和这个肩膀没事(这是我的盲猜cuz没有可行的信息在这里)

+0

非常感谢Antoniossss。它工作。我设法改变JSONObject jsonBreaker =新的JSONObject(result);到JSONArray jsonBreaker = new JSONArray(result); success = String.valueOf(jsonBreaker.getString(0)); message = String.valueOf(jsonBreaker.getString(1));现在错误消失了。非常感谢您的解决方案 – Turbo

+0

如果这是正确的解决方案,请接受答案(在左侧打勾)并正确向上投票(向左箭头) – Antoniossss