2016-08-18 3 views
1

나는 내가 만든 로컬 db에 json 파일을 보내기위한 안드로이드 앱을 만들고 있습니다. 그러나 시작할 때마다 내 gradle 동기화가 실패합니다. 나는 모든 것을 올바른 위치에 놓았지만 (나는 생각한다), 나는 왜 그런지 모른다. 여기 내 Gradle을이다 :android 앱에서 Json을 로컬 db로 보내기

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 24 
    buildToolsVersion "24.0.1" 

    defaultConfig { 
     applicationId "francesco.postjson" 
     minSdkVersion 23 
     targetSdkVersion 24 
     versionCode 1 
     versionName "1.0" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    testCompile 'junit:junit:4.12' 
    compile 'com.android.support:appcompat-v7:24.2.0' 
    classpath 'com.android.tools.build:gradle:2.1.3' 
    compile 'cz.msebera.android:httpclient:4.4.1.1' 
    compile files('libs/httpcore-4.4.4.jar') 
    compile files('libs/okhttp-3.4.1.jar') 
    compile files('libs/commons-codec-1.9.jar') 
    compile files('libs/commons-logging-1.2.jar') 
    compile 'com.squareup.okhttp:okhttp:2.0.0' 
    compile files('libs/httpclient-win-4.5.2.jar') 
    compile files('libs/httpclient-4.5.2.jar') 
    compile files('libs/httpcore-4.4.4.jar') 
    compile files('libs/fluent-hc-4.5.2.jar') 
} 

나는 의존성 이러한 유형을 사용하고 있는데 나는 오류가 있어요 :

Error:(25, 0) Could not find method classpath() for arguments [com.android.tools.build:gradle:2.1.3] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. 
<a href="openFile:C:\Users\Francesco\AndroidStudioProjects\POSTJSON\app\build.gradle">Open File</a> 

내가 다른 곳에서 종속성을 배치해야합니까는? 당신에게

편집 감사합니다 여기에 모든

package francesco.postjson; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.URLConnection; 
import org.json.JSONObject; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.app.Activity; 
import francesco.postjson.Person; 

public class MainActivity extends Activity implements OnClickListener { 

    TextView tvIsConnected; 
    EditText etName,etCountry,etTwitter; 
    Button btnPost; 

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

     // get reference to the views 
     tvIsConnected = (TextView) findViewById(R.id.tvIsConnected); 
     etName = (EditText) findViewById(R.id.etName); 
     etCountry = (EditText) findViewById(R.id.etCountry); 
     etTwitter = (EditText) findViewById(R.id.etTwitter); 
     btnPost = (Button) findViewById(R.id.btnPost); 

     // check if you are connected or not 
     if(isConnected()){ 
      tvIsConnected.setBackgroundColor(0xFF00CC00); 
      tvIsConnected.setText("You are conncted"); 
     } 
     else{ 
      tvIsConnected.setText("You are NOT conncted"); 
     } 

     // add click listener to Button "POST" 
     btnPost.setOnClickListener(this); 

    } 

    public static String POST(String url, Person person){ 
     InputStream inputStream = null; 
     String result = ""; 
     try { 

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

      // 2. make POST request to the given URL 
      HttpPost httpPost = new HttpPost(url); 

      String json = ""; 

      // 3. build jsonObject 
      JSONObject jsonObject = new JSONObject(); 
      jsonObject.accumulate("name", person.getName()); 
      jsonObject.accumulate("country", person.getCountry()); 
      jsonObject.accumulate("twitter", person.getTwitter()); 

      // 4. convert JSONObject to JSON to String 
      json = jsonObject.toString(); 

      // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
      // ObjectMapper mapper = new ObjectMapper(); 
      // json = mapper.writeValueAsString(person); 

      // 5. set json to StringEntity 
      StringEntity se = new StringEntity(json); 

      // 6. set httpPost Entity 
      httpPost.setEntity(se); 

      // 7. Set some headers to inform server about the type of the content 
      httpPost.setHeader("Accept", "application/json"); 
      httpPost.setHeader("Content-type", "application/json"); 

      // 8. Execute POST request to the given URL 
      HttpResponse httpResponse = httpclient.execute(httpPost); 

      // 9. receive response as inputStream 
      inputStream = httpResponse.getEntity().getContent(); 

      // 10. convert inputstream to string 
      if(inputStream != null) 
       result = convertInputStreamToString(inputStream); 
      else 
       result = "Did not work!"; 

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

     // 11. return result 
     return result; 
    } 

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

     switch(view.getId()){ 
      case R.id.btnPost: 
       if(!validate()) 
        Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show(); 
       // call AsynTask to perform network operation on separate thread 
       new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet"); 
       break; 
     } 

    } 
    private class HttpAsyncTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 

      person = new Person(); 
      person.setName(etName.getText().toString()); 
      person.setCountry(etCountry.getText().toString()); 
      person.setTwitter(etTwitter.getText().toString()); 

      return POST(urls[0],person); 
     } 
     // onPostExecute displays the results of the AsyncTask. 
     @Override 
     protected void onPostExecute(String result) { 
      Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show(); 
     } 
    } 

    private boolean validate(){ 
     if(etName.getText().toString().trim().equals("")) 
      return false; 
     else if(etCountry.getText().toString().trim().equals("")) 
      return false; 
     else if(etTwitter.getText().toString().trim().equals("")) 
      return false; 
     else 
      return true; 
    } 
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{ 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
     String line = ""; 
     String result = ""; 
     while((line = bufferedReader.readLine()) != null) 
      result += line; 

     inputStream.close(); 
     return result; 

    } 
} 
+0

Windows를 사용하는 경우 Windows가 C 드라이브를 보호하려고 시도 할 때 프로젝트를 다른 디렉토리에 배치하는 것이 좋습니다. 보안상의 이유로 인해 org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler가 빌드 파일에 액세스 할 수 없습니다. –

답변

0

첫째, JSON을 보내 코드의 공유 부분을 보내는 내 코드입니다.

둘째, 왜 그렇게 많은 의존성을 사용합니까? 어쩌면 당신은 아파치 클래스를 사용하려고 시도하고 있으며, 인터넷의 어딘가에서 이러한 의존성을 발견했다. 코드를 게시 한 후 전체 솔루션을 제공 할 수 있습니다. 그러나이 줄을 제거하려고 시도하십시오 : classpath 'com.android.tools.build:gradle:2.1.3'. 마지막으로 사용되지 않으므로 Apache 클래스 대신 HttpURLConnection을 사용하십시오.

(이 글은 댓글이어야하지만 저의 평판은 낮습니다).

+0

. 또한 나는 그것들 모두를 제거하려고 노력했으나 그것도 사용할 수 없다. – lavendemmia

+0

당신은 50 명 이상의 평판을 가지고 있으며, Turkhan의 질문에 대해 언급 할 수 있어야한다. – halfer

0
classpath 'com.android.tools.build:gradle:2.1.3' 

이것은 모듈 gradle 파일이 아닌 프로젝트 gradle 파일에 주어져야합니다.

아파치 웹 클라이언트가 사용하는 경우, 모듈 Gradle을 전에서 안드로이드 태그 안에

useLibrary 'org.apache.http.legacy'

를 추가합니다. e 이후

buildToolsVersion "24.0.1" 
+0

이제 해당 파일을 제거하고 내 코드에서 httpclient, httppost, ecc ecc를 모두 찾을 수 없습니다. 어떻게 해결할 수 있을까요? – lavendemmia